const db = require('./db')
const bcryptjs = require('bcryptjs')
const jwt = require('jsonwebtoken')
const register = async (req, res, next) => {
  try {
    const { username, password, email } = req.body

    // 参数验证
    if (!username || !password || !email) {
      return res.status(400).json({
        code: 400,
        msg: '所有字段均为必填项'
      });
    }

    // 检查用户名和邮箱唯一性
    const [existing] = await db.query(
      `SELECT user_id FROM users 
       WHERE username = ? OR email = ?`,
      [username, email]
    )

    if (existing.length > 0) {
      return res.status(409).json({
        code: 409,
        msg: '用户名或邮箱已被使用'
      })
    }

    // 密码哈希
    const saltRounds = 10
    const hash = await bcryptjs.hash(password, saltRounds)

    // 创建用户
    const [result] = await db.query(
      `INSERT INTO users (username, password_hash, email)
       VALUES (?, ?, ?)`,
      [username, hash, email]
    )

    res.status(201).json({
      code: 201,
      data: { user_id: result.insertId },
      msg: '注册成功'
    })
  } catch (error) {
    console.error(error)
  }
}
const login = async (req, res, next) => {
  try {
    const { email, password } = req.body

    // 参数验证
    if (!email || !password) {
      return res.status(400).json({
        code: 400,
        msg: '邮箱和密码不能为空'
      });
    }

    // 查找用户
    const [users] = await db.query(
      `SELECT * FROM users 
       WHERE email = ?`,
      [email]
    )

    if (users.length === 0) {
      return res.status(401).json({ code: 401, msg: '用户或密码错误' })
    }

    const user = users[0]
    const valid = await bcryptjs.compare(password, user.password_hash)

    if (!valid) {
      return res.status(401).json({ code: 401, msg: '用户或密码错误' })
    }
    // 生成 JWT
    const token = jwt.sign(
      {
        user_id: user.user_id,
        iat: Math.floor(Date.now() / 1000), // 签发时间（当前时间戳）
        nonce: Math.random().toString(36).substring(2), // 随机字符串
      },
      process.env.JWT_SECRET,
      { expiresIn: '1d' }
    )

    res.json({
      code: 200,
      data: {
        access_token: token,
        expires_in: 86400,
        user: user
      },
      msg: '登录成功'
    })
  } catch (error) {
    console.error(error)
  }
}

const getUserNameById = async (req, res, next) => {
  try {
    const { id } = req.params

    const [users] = await db.query(
      `SELECT username FROM users 
       WHERE user_id = ?`,
      [id]
    )

    if (users.length === 0) {
      return res.status(404).json({ code: 404, msg: '用户不存在' })
    }

    const user = users[0]
    res.json({
      code: 200,
      data: {
        username: user.username
      },
      msg: '获取用户名成功'
    })
  } catch (error) {
    console.error(error)
  }

}

module.exports = { login, register, getUserNameById }